package com.fyz.aaronfjava.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类
 * maxAge为正数的时候代表的是持久化时间，即会话关闭下次会话依旧携带；-1是默认值，表示会话结束即销毁
 * domain保存域，只能在当前域名下访问
 * path是访问路径，在该路径下的请求都能携带cookie（/xxx/ xxx下面的请求都携带）
 * isHttpOnly设置为true的时候表示只能通过http携带，无法通过js方式获取
 */
public class CookieUtil {

    // 保存路径 默认根路径
    private static final String COOKIE_PATH = "/";

    /**
     * 保存 默认保存时间维护在一个会话
     * @param response
     * @param key
     * @param value
     */
    public static void set(HttpServletResponse response, String key, String value) {
        set(response, key, value, -1);
    }

    /**
     * 保存
     * @param response
     * @param key
     * @param value
     * @param maxAge 保存时间
     */
    public static void set(HttpServletResponse response, String key, String value, int maxAge) {
        maxAge = maxAge <= 0 ? -1 : maxAge;
        set(response, key, value, null, COOKIE_PATH, maxAge, false);
    }

    /**
     * 保存
     * @param response
     * @param key
     * @param value
     * @param domain 保存域
     * @param path 保存路径
     * @param maxAge
     * @param isHttpOnly
     */
    public static void set(HttpServletResponse response, String key, String value, String domain, String path,int maxAge, boolean isHttpOnly) {
        Cookie cookie = new Cookie(key, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        cookie.setHttpOnly(isHttpOnly);
        response.addCookie(cookie);
    }

    /**
     * 查询value
     *
     * @param request
     * @param key
     * @return
     */
    public static String getValue(HttpServletRequest request, String key) {
        Cookie cookie = get(request, key);
        if (cookie != null) {
            return cookie.getValue();
        }
        return StringUtil.BLANK;
    }

    /**
     * 查询Cookie
     *
     * @param request
     * @param key
     */
    public static Cookie get(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 删除Cookie
     *
     * @param request
     * @param response
     * @param key
     */
    public static void remove(HttpServletRequest request, HttpServletResponse response, String key) {
        Cookie cookie = get(request, key);
        if (cookie != null) {
            set(response, key, "", null, COOKIE_PATH, 0, true);
        }
    }

}
